package com.example.orchid.coordinatorlayoutdemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.orchid.coordinatorlayoutdemo.R;
import com.example.orchid.coordinatorlayoutdemo.activity.TwoActivity;
import com.example.orchid.coordinatorlayoutdemo.adapter.ZhihuRecyclerAdapter;
import com.example.orchid.coordinatorlayoutdemo.client.ApiManger;
import com.example.orchid.coordinatorlayoutdemo.entity.NewsListEntity;
import com.example.orchid.coordinatorlayoutdemo.entity.NewsListEntity.StoriesEntity;
import com.example.orchid.coordinatorlayoutdemo.utils.DateUtils;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 仿知乎目录页面
 * Created by Orchid on 2015-10-27.
 */
public class ZhihuFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    private View view;

    private RecyclerView recyclerView;
    private SwipeRefreshLayout mRefreshLayout;
    //上次listView滚动到最下方时，itemId
    private int mListViewPreLast = 0;
    private LinearLayoutManager mLayoutManager;
    private ZhihuRecyclerAdapter adapter;
    private ArrayList<StoriesEntity> mNewsList = null;
    //记录最后一次刷新的时间 防止一段时间内多次刷新
    private long lastRefresh;
    //记录最下面新闻对应的时间
    private String mCurrentDate = null;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.refresh_item, container, false);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_widget);
        mRefreshLayout.setColorSchemeResources(android.R.color.holo_green_dark, android.R.color.holo_green_light,
                android.R.color.holo_orange_light, android.R.color.holo_red_light);
        mRefreshLayout.setOnRefreshListener(this);

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);


        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE &&
                        mListViewPreLast + 1 == adapter.getItemCount()) {
                    mRefreshLayout.setRefreshing(true);
                    Toast.makeText(getActivity(), "加载更多数据", Toast.LENGTH_LONG).show();
                    ApiManger.getLastNewsList(mCurrentDate).subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread()).map(newsListEntity -> mergerData(newsListEntity))
                            .subscribe(result -> {
                                        loadMoreDate(result);
                                        setAdapter(mNewsList);
                                        mRefreshLayout.setRefreshing(false);
                                    },
                                    throwable -> {
                                        Log.e("Tag", throwable.toString());
                                        mRefreshLayout.setRefreshing(false);
                                    }

                            );

                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                mListViewPreLast = mLayoutManager.findLastCompletelyVisibleItemPosition();
            }
        });

        mLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(mLayoutManager);
        recyclerView.addItemDecoration(new HorizontalDividerItemDecoration.Builder(getContext()).build());
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        initData();
    }

    private void initData() {
        // TODO: 2015-10-29 要解决刷新时的加载条的显示问题
        mRefreshLayout.post(() -> mRefreshLayout.setRefreshing(true));
        mRefreshLayout.setRefreshing(true);
        mCurrentDate = DateUtils.getCurrentDate(DateUtils.YYYYMMDD);
        Observable.zip(
                ApiManger.getNewsList(),
                ApiManger.getLastNewsList(mCurrentDate),
                (newsListEntity, newsListEntity2) -> mergerData(newsListEntity, newsListEntity2))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(result -> {
                            resultToList(result, false);
                            setAdapter(mNewsList);
                            adapter.setOnItemClickListener((v, o) ->
                                    startActivity(new Intent(getActivity(), TwoActivity.class)));
                            mRefreshLayout.post(() -> mRefreshLayout.setRefreshing(false));
                        },
                        throwable -> {
                            Log.e("Tag", throwable.toString());
                            mRefreshLayout.setRefreshing(false);
                        }

                );

    }

    private List<NewsListEntity> mergerData(NewsListEntity... listEntity) {
        List<NewsListEntity> data = new ArrayList<>(listEntity.length);
        Collections.addAll(data, listEntity);
        return data;
    }

    @Override
    public void onRefresh() {
        //大于一秒方个通过
        if (System.currentTimeMillis() - lastRefresh <= 1000 * 60 * 3) {
            mRefreshLayout.setRefreshing(false);
            showToast("请勿在短时间内多次刷新");
            return;
        }
        lastRefresh = System.currentTimeMillis();
        ApiManger.getNewsList().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .map(newsListEntity -> mergerData(newsListEntity))
                .subscribe(result -> {
                            if (result != null && !result.isEmpty()) {
                                loadDate(result);
                                setAdapter(mNewsList);
                                mRefreshLayout.setRefreshing(false);
                            }
                        },
                        throwable -> {
                            Log.e("Tag", throwable.toString());
                            mRefreshLayout.setRefreshing(false);

                        }
                );
    }

    /**
     * 接口结果转换成带时间标签的list
     *
     * @param result     接口返回的结果集
     * @param isLoadMore 是否为加载更多的动作
     */
    private void resultToList(NewsListEntity result, boolean isLoadMore) {
        StoriesEntity tagNewsEntity = new StoriesEntity();
        tagNewsEntity.setIsTag(true);
        tagNewsEntity.setTitle(result.getDate());
        if (!isLoadMore) {
            mNewsList = new ArrayList<>();
        }

        mNewsList.add(tagNewsEntity);
        mNewsList.addAll(result.getStories());
        mCurrentDate = result.getDate();
    }

    /**
     * 接口结果转换成带时间标签的list
     *
     * @param result     接口返回的结果集
     * @param isLoadMore 是否为加载更多的动作
     */
    private void resultToList(List<NewsListEntity> result, boolean isLoadMore) {

        if (!isLoadMore) {
            mNewsList = new ArrayList<>();
        }
        for (NewsListEntity newsListEntity : result) {
            StoriesEntity tagNewsEntity = new StoriesEntity();
            tagNewsEntity.setIsTag(true);
            tagNewsEntity.setTitle(newsListEntity.getDate());
            mNewsList.add(tagNewsEntity);
            mNewsList.addAll(newsListEntity.getStories());
            mCurrentDate = newsListEntity.getDate();
        }
    }

    private void showToast(String str) {
        Toast.makeText(this.getActivity(), str, Toast.LENGTH_SHORT).show();

    }

    private void loadDate(List<NewsListEntity> result) {
        resultToList(result, false);
    }

    private void loadMoreDate(List<NewsListEntity> result) {
        resultToList(result, true);
    }

    private void setAdapter(List<StoriesEntity> newsList) {
        if (adapter == null) {
            adapter = new ZhihuRecyclerAdapter(getActivity(), (ArrayList<StoriesEntity>) newsList);
            recyclerView.setAdapter(adapter);
        } else {
            adapter.updateData((ArrayList<StoriesEntity>) newsList);
        }
    }


}
